(() => {
  const ICON_ON = 'img/ic_nav_tweet_actived.png',
        ICON_OFF = 'img/ic_nav_tweet_normal.png',
        TITLE_ON = '动弹ing',
        TITLE_OFF_PAUSED = '休息中...',
        LOCAL_KEY_ON = 'on',
        LOCAL_KEY_LAST = 'last',
        domParser = new DOMParser(),
        installed = localStorage.getItem('installed') !== null

  function nullDefault(val, defaultVal) {
    return val === null ? defaultVal : val
  }

  // 拉取动弹
  let on = nullDefault(JSON.parse(localStorage.getItem(LOCAL_KEY_ON)), true),
      lastTweetId = nullDefault(JSON.parse(localStorage.getItem(LOCAL_KEY_LAST)), 1),
      timer
  function checkTweet() {
    if (on) {
      fetch(`https://www.oschina.net/widgets/check-top-log?last=${lastTweetId}`, { credentials: 'include' })
        .then(res => {
          return res.text()
        })
        .then(res => {
          if (res.trim().length) {
            let doc = domParser.parseFromString(res, 'text/html'),
                tweets = Array.from(doc.body.children)
                  .map(tweetLi => ({

                    id: parseInt(tweetLi.getAttribute('log')),
                    nick: tweetLi.querySelector('.user a').textContent,
                    avatar: tweetLi.querySelector('.portrait img').getAttribute('src'),
                    content: Array.from(tweetLi.querySelector('.log').childNodes).map(node => {
                      return node.nodeType === 3 || node.tagName === 'A' ? node.textContent
                        : node.tagName === 'EMOJI' ? `:${node.getAttribute('data-name')}:`
                        : node.tagName === 'IMG' ? `[${node.getAttribute('alt')}]`
                        : node.outerHTML // 未知
                    }).join(''),
                    hasPic: tweetLi.querySelector('img[src*="img.gif"]'),
                    url: tweetLi.querySelector('.time a').href
                  }))

            tweets.forEach(tweet => {
              chrome.notifications.create(tweet.url, {
                type: 'basic',
                title: `${tweet.nick}：`,
                message: `${tweet.content}${tweet.hasPic ? '🖼' : ''}`,
                iconUrl: `${tweet.avatar.startsWith('/') ? 'https://www.oschina.net' : ''}${tweet.avatar}`
              })
            })

            lastTweetId = Math.max(lastTweetId, tweets[0].id)
            localStorage.setItem(LOCAL_KEY_LAST, JSON.stringify(lastTweetId))
          }
        })
        .catch(e => 0)
    }
  }
  function startChecking() {
    timer = setInterval(checkTweet, 10e3)
    checkTweet()
  }
  function stopChecking() {
    clearInterval(timer)
    chrome.notifications.getAll(notifications => {
      Object.keys(notifications).forEach(id => chrome.notifications.clear(id))
    })
  }
  function updateState() {
    let icon, title
    if (on) {
      icon = ICON_ON
      title = TITLE_ON
      startChecking()
    } else if (!on) {
      icon = ICON_OFF
      title = TITLE_OFF_PAUSED
      stopChecking()
    }
    chrome.browserAction.setIcon({
      path: icon
    })
    chrome.browserAction.setTitle({
      title: title
    })
  }
  chrome.browserAction.onClicked.addListener(() => {
    on = !on
    updateState()
    localStorage.setItem(LOCAL_KEY_ON, JSON.stringify(on))
  })
  chrome.notifications.onClicked.addListener(tweetUrl => {
    window.open(tweetUrl)
    chrome.notifications.clear(tweetUrl)
  })

  updateState()
})()